import type { ReactElement } from 'react';
import React, { useRef, useState } from 'react';
import { useIntl } from 'umi';
import request from '@/utils/request';
import ProTable, { ActionType } from '@ant-design/pro-table';
import type { SearchConfig } from '@ant-design/pro-table/lib/components/Form/FormRender';
import { Button, ButtonProps, message } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import { RecordCreatorProps } from '@ant-design/pro-table/lib/components/EditableTable';

const apiURLReport = '/api/services/app/ERPReports/';
export interface FCProps {
  title?: string | ReactElement;
  callback?: (item: any) => void;
  bordered?: boolean;
  search?: false | SearchConfig;
  rowKey?: string;
  sysReportName: string;
  params?: any;
  toolBarRender?: JSX.Element[] | false;
  rowSelection?: any;
  scroll?: any;
  freshNum?: number;
  /** 数据载入回调 */
  onload?: (data: any) => void;
  footer?: any;
  recordCreatorProps?:
  | (RecordCreatorProps<any> &
    ButtonProps & {
      creatorButtonText?: React.ReactNode;
    })
  | false;
  editable?: boolean;
  dataSource?: any[];
  /** 行编辑保存方法 */
  onRowSave?: (rowKey: any, data: any, row: any) => Promise<void>;
  /** 操作列显示文本 */
  optionText?: string;
}
const OperpQuery: React.FC<FCProps> = (props: FCProps) => {
  const intl = useIntl();
  const [dataSource, setDataSource] = useState<any>(props.dataSource || []);
  const [pageSize, setPageSize] = useState<number>(10);
  const [report, setReport] = useState<any>({});
  const [dyColumns, setDyColumns] = useState<any>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const actionRef = useRef<ActionType>();
  const exportBtn = [
    <Button
      type="link"
      key="out"
      loading={loading}
      onClick={() => handlerExport(dataSource, report)}
      hidden={report?.hiddenExport}
      icon={<DownloadOutlined />}
      size="small"
    >
      {intl.formatMessage({
        id: 'pages.export',
      })}
    </Button>,
  ];
  const runSQL = async (obj: any, params: any = null) => {
    if (!obj || !obj.id) {
      return [];
    }
    const result: any = {
      data: [],
      total: 0,
    };
    setDataSource([]);
    const _args = {
      ...params,
      ...props.params,
    };
    await request(apiURLReport + 'RunSQL', {
      method: 'POST',
      data: { id: obj.id, args: _args },
    }).then((response) => {
      if (response) {
        if (response.success) {
          result.data = response.result;
          result.total = response.totalCount;
          setDataSource(response.result);
        }
      }
    });
    return result;
  };

  const getColumns = () => {
    request(apiURLReport + 'GetByName', {
      method: 'GET',
      params: { name: props.sysReportName, rptype: 'SysRpt' },
    }).then((response) => {
      if (response) {
        if (response.success) {
          try {
            const result = response.result;
            if (result.reportName) {              
              if(props.editable){
                const actionColumn = {
                  title: intl.formatMessage({ id: 'pages.searchTable.titleOption', defaultMessage: 'option' }),
                  valueType: 'option',
                  fixed: 'right',
                  width: 100,
                  render: (_: any, record: any) => (
                    <span>
                      <a onClick={() => {
                          actionRef.current?.startEditable?.(record.RowId);
                        }}>
                        {props.optionText ? props.optionText : intl.formatMessage({ id: 'option', defaultMessage: 'option' })}
                      </a>
                    </span>
                  ),
                };
                setDyColumns([...result.filedList, actionColumn]);
              }
              else{
                setDyColumns(result.filedList);
              }
              setReport(result);
              runSQL(result, props.params);
            } else {
              message.warn(intl.formatMessage({id:'pages.sysReportMissing'}) +'(' + props.sysReportName + ')');
            }
          } catch { }
        }
      }
    });
  };

  const handlerExport = async (data: any, record: any) => {
    if (!data || data.length <= 0) {
      message.warning(intl.formatMessage({id:'pages.exportNoData'}));
      return;
    }
    setLoading(true);
    const resp = await request('/api/Excel/ExportReport', {
      method: 'POST',
      responseType: 'blob',
      data: {
        args: data,
        reportId: record.id,
      },
    });
    const url = window.URL.createObjectURL(resp);
    const a = document.createElement('a');
    a.href = url;
    a.download = record.reportName + '.xls';
    a.click();
    setLoading(false);
  };
  React.useEffect(() => {
    getColumns();
  }, [props.freshNum]);

  React.useEffect(() => {
    setDataSource(props.dataSource || []);
  }, [props.dataSource]);

  return (
    <ProTable
      actionRef={actionRef}
      headerTitle={
        props.title
          ? intl.formatMessage({
            id: report.reportName ? report.reportName : 'report',
          })
          : ''
      }
      editable={{
        type: 'multiple',
        editableKeys,
        onChange: setEditableRowKeys,
        actionRender: (row, config, dom) => [dom.save, dom.cancel],
         onSave: props.onRowSave ? props.onRowSave : async (rowKey, data, row) => { },
      }}
      dataSource={dataSource}
      columns={dyColumns}
      rowKey={report?.rowKey ? report?.rowKey : 'Id'}
      bordered={props.bordered ? props.bordered : report?.bordered}
      search={
        props.search
          ? props.search
          : {
            filterType: report?.filterType,
          }
      }
      defaultSize="small"
      request={async (params = {}) => {
        return runSQL(report, params);
      }}
      pagination={{
        pageSize,
        onChange: (page, pageSize) => setPageSize(pageSize),
      }}
      toolBarRender={() =>
        props.toolBarRender ? props.toolBarRender.concat(exportBtn) : exportBtn
      }
      rowSelection={props.rowSelection}
      scroll={props.scroll}
      onLoad={(e) => {
        if (props.onload) {
          props.onload(e);
        }
      }}
      onRow={(record) => {
        return {
          onDoubleClick: () => {           
            if (props.callback) {
              props.callback(record);
            }
          },
        };
      }}
      footer={props.footer}
    />
  );
};
export default OperpQuery;
